import type { SetupContext } from "vue";

import { LoadMore } from "@/components/LoadMore/loadMore";

import type { BasicTableProps } from "../basicTable";
import type { BasicTableEmits } from "../basicTable";
import { DataSourceMode } from "../basicTable";

export const useTable = <T>(
  props: BasicTableProps,
  emits: SetupContext<BasicTableEmits<T>>["emit"]
) => {
  const loadStatus = ref<LoadMore>(LoadMore.LoadMore);
  const loading = ref(false);
  const dataSources = ref<T[]>([]);
  const totalNumber = ref<number>(0);
  const page = ref({
    page: 1,
    size: props.defaultPageSize,
  });

  // 获取表格列表
  async function getDatsSource() {
    if (!props.request) {
      return;
    }

    const { list = "list", total = "total" } = props.fieldNames;
    if (DataSourceMode.Loadmore === props.dataSourceMode) {
      if (loadStatus.value === LoadMore.NoMore) {
        return;
      }
      loadStatus.value = LoadMore.Loading;
    }

    loadStatus.value = LoadMore.Loading;
    loading.value = true;
    const result = await props.request({
      ...page.value,
      ...(props.params || {}),
    });
    if (result) {
      totalNumber.value = Number(result[total] || 0);
      if (DataSourceMode.Loadmore === props.dataSourceMode) {
        dataSources.value = dataSources.value.concat(result[list] || []);
        loadStatus.value =
          dataSources.value.length < totalNumber.value
            ? LoadMore.LoadMore
            : LoadMore.NoMore;
      } else {
        dataSources.value = result[list] || [];
      }
    }
    emits("requestEnd", dataSources.value as T[]);
    loading.value = false;
  }

  async function resetQuery() {
    dataSources.value = [];
    totalNumber.value = 0;
    page.value.page = 1;
    loadStatus.value = LoadMore.LoadMore;
    await getDatsSource();
  }

  return {
    loadStatus,
    loading,
    page,
    dataSources,
    totalNumber,
    getDatsSource,
    resetQuery,
  };
};
